
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select
from task.tools.logger import  GetLogger
logger = GetLogger().get_logger()
class Base:
    def __init__(self,driver):
        logger.info('开始初始化driver')
        self.driver=driver

    def base_find_element(self,loc,timeout=30,poll_frequency=0.5):
        '''
        loc= By.CSS_SELECTOR,'元素的具体位置的值'
        :param loc:
        :return:
        '''
        # el=self.driver.find_element(*loc)
        logger.info('开始定位元素：{}元素的最多等待时间是{}'.format(loc,timeout))
        el=WebDriverWait(self.driver,timeout=timeout,poll_frequency=poll_frequency).until(lambda x:x.find_element(*loc))
        return el
    def base_click(self,loc):
        logger.info('开始点击：{}元素'.format(loc))
        self.base_find_element(loc).click()

    def base_input(self,loc,value):
        logger.info('开始在：{}元素输入{}'.format(loc,value))
        el=self.base_find_element(loc)
        el.clear()
        el.send_keys(value)

    def base_switch_window(self,title):
        logger.info('开始切换窗口,窗口标题是{}'.format(title))
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            if self.driver.title == title:
                break

    def base_switch_frame(self,frame):
        #好处是可以调用log日志
        logger.info('开始切换frame{}'.format(frame))
        self.driver.switch_to.frame(frame)
    #切回默认的iframe
    def base_default_iframe(self,frame):
        self.driver.switch_to.default_content(frame)

    def base_select(self,js,loc,text):
        '''
        下拉框选择
        eg:js='document.querySelectorAll("select")[0].style.display="inline"'
        :param js:
        :param loc:
        :param text:
        :return:
        '''
        logger.info('开始下拉框选择：js是{},元素是{}，选择可是文本框是{}'.format(js,loc,text))
        self.driver.execute_script(js)
        select=self.base_find_element(loc)
        Select(select).select_by_visible_text(text)
    def base_scroll(self):
        logger.info('开始滑动页面')
        js = 'window.scrollTo(0,5000)'
        self.driver.execute_script(js)

    @property
    def base_page_source(self):
        return self.driver.page_source